package org.shj.thread.basic;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

import org.shj.thread.util.Util;

/**
 *
 * @author Shen Huang Jian
 * @date 2018-01-02 16:30:25
 */
public class SemaphoreDemo {

	private static final int THREAD_COUNT = 30;
	private static ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);

	//只允许有10个通行证
	private static Semaphore s = new Semaphore(10);
	
	public static void main(String[] args){
		for(int i = 0 ; i < THREAD_COUNT; i++){
			int ind = i;
			executor.execute(() -> {
				try{
					s.acquire();//如果已经有10个线程获得了通行证，则当前线程会被阻塞，直到其它线程释放通行证
					System.out.println(ind + " save data");
					Util.sleep(1);
					s.release();
				}catch(Exception e){

				}
			});
		}
		executor.shutdown();
	}
}
